package accs.model;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public abstract class SimpleAccountChecker implements AccountChecker {
	
	public Account login(String user, String password) throws Exception {
		DefaultHttpClient client=new DefaultHttpClient();
		
		if(isPostRequest()) {
			HttpPost post=new HttpPost(getLoginUrl());
			List<NameValuePair> list=new ArrayList<NameValuePair>();
			getLoginParams(user,password,list);
			post.setEntity(new UrlEncodedFormEntity(list,"utf-8"));
			
			EntityUtils.consume(client.execute(post).getEntity());
		} else {
			URIBuilder builder=new URIBuilder(getLoginUrl());
			List<NameValuePair> list=new ArrayList<NameValuePair>();
			getLoginParams(user,password,list);
			for(NameValuePair pair:list) {
				builder.addParameter(pair.getName(),pair.getValue());
			}
			HttpGet get=new HttpGet(builder.build());
			
			EntityUtils.consume(client.execute(get).getEntity());
		}
		
		HttpGet get=new HttpGet(getDataUrl());
		BufferedReader reader=new BufferedReader(new InputStreamReader(client.execute(get).getEntity().getContent(),"utf-8"));
		return readAccount(reader);
	}
	
	protected boolean isPostRequest() {
		return true;
	}
	
	protected abstract String getLoginUrl();
	protected abstract void getLoginParams(String user, String pass, List<NameValuePair> list);
	protected abstract String getDataUrl();
	protected abstract Account readAccount(BufferedReader reader);
}